package com.gexin.controller.xapp.product;

import com.gexin.controller.system.LoginController;
import com.gexin.core.interceptor.XAppSafeInterceptor;
import com.gexin.core.web.AppController;
import com.gexin.model.agent.Agent;
import com.gexin.model.agent.AgentCity;
import com.gexin.model.agent.AgentLevel;
import com.gexin.model.order.OrderCart;
import com.gexin.model.product.ProductSku;
import com.gexin.model.product.ProductType;
import com.gexin.model.product.Products;
import com.gexin.model.user.UserCollect;
import com.gexin.model.weixin.WeixinUser;
import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.ext.route.ControllerBind;
import com.jfinal.log.Log;
import org.apache.commons.lang3.StringUtils;

import java.math.BigDecimal;
import java.util.*;

/**
 * 商品接口
 *
 * @author 肖得明
 */
@Before(XAppSafeInterceptor.class)//统一错误拦截
@ControllerBind(controllerKey = "/xapp/app/product")
public class ProductsController extends AppController {
	static Log log = Log.getLog(LoginController.class);


	@Clear
	public void mall(){
		String title =getPara("title");
		Map<String,Object> map =new HashMap<>();
		//预售商品
		String presale_sql="select * from  t_product_type where pid =0 and  state= 0 and del_state = 0  and find_in_set(2,show_type)  ";
		if(!StringUtils.isEmpty(title)){
			presale_sql=presale_sql+" and type_name like '%"+title+"%' ";
		}
		presale_sql=presale_sql+"order by sort asc";
		List<ProductType> presale_list = ProductType.dao.find(presale_sql);
		for(ProductType t1:presale_list){//获取所有
			String p_type_sql="select * from  t_product_type where state= 0 and del_state = 0  and pid = ?    ";
			if(!StringUtils.isEmpty(title)){
				p_type_sql=p_type_sql+" and type_name like '%"+title+"%' ";
			}
			p_type_sql=p_type_sql+" order by sort asc ";
			List<ProductType> pType =ProductType.dao.find(p_type_sql,t1.getId());
			for(ProductType p1:pType){
				List<Products> products=Products.dao.getProductsByAttrType(2,p1.getId(),title);
				for(Products p :products){
					p.put("stock_text", ProductSku.dao.cache_getStockByProduct(p.getId()));
				}
				p1.put("products",products);
			}
			t1.put("sub_type",pType);
		}
		map.put("presale_product",presale_list);
		//普通商品
		String ordinary_sql="select * from  t_product_type where pid =0 and state= 0 and del_state = 0  and find_in_set(1,show_type)  ";
		if(!StringUtils.isEmpty(title)){
			ordinary_sql=ordinary_sql+" and type_name like '%"+title+"%' ";
		}
		ordinary_sql=ordinary_sql+"order by sort asc";
		List<ProductType> ordinary_list = ProductType.dao.find(ordinary_sql);
		for(ProductType t1:ordinary_list){//获取所有
			String p_type_sql="select * from  t_product_type where state= 0 and del_state = 0  and pid = ?   ";
			if(!StringUtils.isEmpty(title)){
				p_type_sql=p_type_sql+" and type_name like '%"+title+"%' ";
			}
			p_type_sql=p_type_sql+" order by sort asc ";
			List<ProductType> pType =ProductType.dao.find(p_type_sql,t1.getId());
			for(ProductType p1:pType){
				List<Products> products=Products.dao.getProductsByAttrType(1,p1.getId(),title);
				for(Products p :products){
					p.put("stock_text", ProductSku.dao.cache_getStockByProduct(p.getId()));
				}
				p1.put("products",products);
			}
			t1.put("sub_type",pType);
		}
		map.put("ordinary_product",ordinary_list);
		success(map);
	}

	@Clear
	public void loadType(){
		List<ProductType> type_list = ProductType.dao.find("select * from  t_product_type where pid =0 and state= 0 and del_state = 0  order by sort asc ");
		success(type_list);
	}

	@Clear
	public void loadSubType(){
		Integer type_id =getParaToInt("type_id");
		List<ProductType> type_list = ProductType.dao.find("select * from  t_product_type where pid =? and state= 0 and del_state = 0  order by sort asc ",type_id);
		success(type_list);
	}

	public void loadTypeProductAgent(){
		Integer type_id =getParaToInt("type_id");
		String cityId = getPara("city_id");
		String agentId = getPara("agent_id");
		String name =getPara("name");
		List<ProductType> list =new LinkedList<>();
		List<ProductType> pType =ProductType.dao.find("select * from  t_product_type where state= 0 and del_state = 0  and pid = ?  order by sort asc ",type_id);
		for(ProductType p1:pType){
			List<Products> products=Products.dao.getProductsByAgent(p1.getId(),name);
			for(Products p:products){
				Agent agent = Agent.dao.findById(agentId);
				AgentLevel agentLevel =null;
				if(Agent.TYPE_NORM.equals(agent.getType())){
					Integer levelId = agent.getLevelId();
					agentLevel = AgentLevel.dao.findById(levelId);

				}else{
					AgentCity agentCity = AgentCity.dao.findById(cityId);
					if(agentCity!=null){
						agentLevel = AgentLevel.dao.findById(agentCity.getLevelId());
					}
				}
				if(agentLevel==null||agentLevel.getDiscount()==null){
					BigDecimal agentPrice = p.getPrice();
					p.put("agentPrice",agentPrice);
				}else{
					BigDecimal agentPrice = p.getPrice().multiply(agentLevel.getDiscount());
					p.put("agentPrice",agentPrice);
				}
			}
			p1.put("products",products);
			if(products.size()>0){
				list.add(p1);
			}
		}
		success(list);
	}

	@Clear
	public void loadTypeProduct(){
		Integer type_id =getParaToInt("type_id");
		Integer arrt_type=getParaToInt("attr_type",2);
		String name =getPara("name");
		List<ProductType> pType =ProductType.dao.find("select * from  t_product_type where state= 0 and del_state = 0  and pid = ?  order by sort asc ",type_id);
		for(ProductType p1:pType){
			List<Products> products=Products.dao.getProductsByAttrType(arrt_type,p1.getId(),name);
			p1.put("products",products);
		}
		success(pType);
	}

	@Clear
	public void list() {
		Integer type = getParaToInt("type");
		if (type == null) {
			fail("类型不能为空！");
			return;
		}
		String sql = "SELECT id,point_price,product_name,stock_count,image_center,attr_type,online_state,price from  t_products where online_state=1 and examine_state=1 and attr_type=?";
		List<Products> list = Products.dao.find(sql, type);
		if (list.size() > 0) {
			success(list);
		} else {
			fail("没有数据");
		}
	}

	@Clear
	public void detail() {
		Integer product_id = getParaToInt("id");
		Map result = Products.dao.getProductsDetailByID(product_id);
		WeixinUser authUser = getAuthUser();
		if(authUser==null){
			result.put("isCollection",false);
		}else{
			UserCollect userCollect = UserCollect.dao.findByProductIdAndUserId(product_id , authUser.getId());
			result.put("isCollection",userCollect!=null);
		}
		success(result);
	}

	//添加到购物车
	public void addCart(){
		Integer product_id =getParaToInt("product_id");
		String sku_id=getPara("sku_id");
		Integer buy_count=getParaToInt("buy_count",1);
		OrderCart cart =new OrderCart();
		Products products =Products.dao.findById(product_id);
		if(products==null || products.getOnlineState()!=1){
			fail("抱歉，此商品不存在或已删除");
			return;
		}
		if(products.getAttrType()!=1){
			fail("抱歉，此商品不能放入购物车");
			return;
		}
		if(products.getStockCount()<=0){
			fail("抱歉，此商品库存数量不足");
			return;
		}
		ProductSku sku =ProductSku.dao.getById(sku_id);
		if(sku!=null){
			if(sku.getStockCount()<=0){
				fail("抱歉，此商品SKU库存数量不足");
				return;
			}
			cart.setSkuId(sku_id);
			cart.setSkuTxt(sku.getSkuText());
			cart.setUnitPrice(sku.getPrice());
		}else{
			cart.setUnitPrice(products.getPrice());
		}
		cart.setUserId(getAuthUser().getId()+"");
		cart.setProductId(products.getId());
		cart.setNums(buy_count);
		cart.setCreatetime(new Date());
		cart.save();
		success("添加成功");
	}

	public void delCart(){
		String cart_id =getPara("cart_id");
		OrderCart.dao.deleteById(cart_id);
		success("移除成功");
	}

	//用户的购物车
	public void myCart(){
		List<OrderCart> list =new ArrayList<>();
		List<OrderCart> cart_list =OrderCart.dao.findByUserAll(getAuthUser().getId());
		for(OrderCart c:cart_list){
			Products products =Products.dao.findById(c.getProductId());
			if(products!=null && products.getStockCount()>0 && products.getOnlineState()==1 && products.getDelState()==false) {
				if(!StringUtils.isEmpty(c.getSkuId())){
					ProductSku sku =ProductSku.dao.getById(c.getSkuId());
					if(sku.getStockCount()>0){
						list.add(c);
					}
				}else{
					list.add(c);
				}
			}
		}
		success(list);
	}

}
